package org.example.resource;

import java.io.*;

public class ResourceReader {
    private static final Integer BUFFER_SIZE = 4096;

    /**
     * 推荐
     *
     * @param path
     * @return
     * @throws IOException
     */
    public String read(String path) throws IOException {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = ResourceReader.class.getClassLoader().getResourceAsStream(path);
            out = new ByteArrayOutputStream(BUFFER_SIZE);
            copy(in, out);
            return new String(out.toByteArray());
        } finally {
            close(in);
            close(out);
        }
    }

    /**
     * 不推荐
     *
     * @param path
     * @return
     * @throws IOException
     */
    @Deprecated
    public String read_deprecated(String path) throws IOException {
        InputStream in = null;
        InputStreamReader isr = null;
        BufferedReader reader = null;
        try {
            in = ResourceReader.class.getClassLoader().getResourceAsStream(path);
            isr = new InputStreamReader(in);
            reader = new BufferedReader(isr);
            StringBuilder builder = new StringBuilder();
            String line = null;
            String br = System.getProperty("line.separator");
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(br);
            }
            return builder.toString();
        } finally {
            close(reader);
            close(isr);
            close(in);
        }
    }

    private void close(Closeable closeable) throws IOException {
        if (closeable != null) {
            closeable.close();
        }
    }

    private void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        out.flush();
    }
}
